package com.elantra.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.elantra.service.LoginService;
import com.elantra.util.QRCodeUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
	protected Logger logger = Logger.getLogger(getClass());



	@Autowired
	private LoginService loginService;

	@RequestMapping("/login")
	public String login(Integer lo,HttpServletRequest req){
		return "admin/login";
	}

	/**
	 * 账号登陆
	 * @param request
	 * @param response
	 * @param account
	 * @param pwd
	 * @return
	 */
	@RequestMapping("/doLogin")
	@ResponseBody
	public JSONObject doLogin(HttpServletRequest request, HttpServletResponse response, String account, String pwd){
		Cookie cookie=new Cookie("JSESSIONID", request.getRequestedSessionId());
		cookie.setMaxAge(1000*60*60*24*30);
		response.addCookie(cookie);
		return loginService.doLogin(account, pwd,request.getRemoteAddr(),request.getRemoteHost());
	}
	/**
	 *
	 */
	@RequestMapping("/loginQRCode")
	public void loginQRCode(HttpServletRequest request,HttpServletResponse response,Integer width,Integer height,String uuid){
		String path=request.getRequestURL().toString().replace(request.getRequestURI(),request.getContextPath()+"/download.html") ;//"http://www.project-5d.com/login.do";
		//String uuid=UUID.randomUUID().toString();
		System.out.println("request.getRequestURL():"+request.getRequestURL());
		String url = path+"?token="+uuid;
		try {
			int iWidth = (width == null ? 200 : width);
			int iHeight = (height == null ? 200 : height);
			QRCodeUtil.createRqCode(url, iWidth, iHeight, response.getOutputStream());
			logger.info(String.format("生成二维码成功： url： %s", url));
		} catch (Exception e) {
			logger.error(String.format("生成二维码失败： url： %s", url), e);
		}
	}
}
